package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetRecord(uid int) ([]*models_main.UserTask, error) {
	o := make([]*models_main.UserTask, 0)
	err := mysql.GetRTable(&models_main.UserTask{}).
		Raw("SELECT * FROM db_user_task WHERE uid = ? AND is_received=1 ORDER BY create_time DESC", uid).
		Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, err
}

func GetUserTasksParam(param map[string]interface{}, order string, page, size int) ([]*models_main.UserTask, error) {
	o := make([]*models_main.UserTask, 0)
	err := mysql.Condition(mysql.GetRTable(&models_main.UserTask{}), param, "", order, page, size).
		Find(&o).
		Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, err
}

func GetUserTaskParam(param map[string]interface{}) (*models_main.UserTask, error) {
	o := &models_main.UserTask{}
	err := mysql.Condition(mysql.GetRTable(&models_main.UserTask{}), param, "", "", 0, 0).
		Order("id desc").Limit(1).
		Find(&o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, err
}

func UpdateUserTaskByTx(tx *gorm.DB, column string, value interface{}, id int) error {
	err := tx.Model(&models_main.UserTask{}).
		Where("id", id).
		Update(column, value).Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}

func InsertUserTaskByTx(tx *gorm.DB, userTask *models_main.UserTask) error {
	err := tx.Create(userTask).Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}

func GetUserTaskByTaskIds(taskId []uint8) ([]*models_main.UserTask, error) {
	o := make([]*models_main.UserTask, 0)
	table := mysql.GetRTable(&models_main.UserTask{})
	err := table.Where("task_id=?", taskId).Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
		return nil, err
	}
	return o, nil
}
